const koa = require("koa");
const cors = require("koa2-cors");
const app = new koa();
const koaBody = require("koa-body");
const config = require("./config");
const router = require("koa-router")();
const sharp = require("sharp");

let blank = "https://nc-it.cn/wx_koa_server/wxres/image/blank.svg"

const fs = require("fs");

let util = require("./util");

app.use(cors());
app.use(
    koaBody({
        multipart: true,
        formidable: {
            maxFileSize: 200 * 1024 * 1024 // 设置上传文件大小最大限制，默认2M
        }
    })
);

router.post("/emp_file_service/upload", async ctx => {
    let result = await util.saveFile(ctx.request.body.files.file);
    ctx.body = result;
});

router.get("/emp_file_service/file/:id", async ctx => {
    try {
        let file = await util.getFile(ctx.params.id);
        ctx.type = file.type;
        ctx.body = fs.readFileSync(file.path);
    } catch (e) {
        ctx.type = "image/svg+xml"
        let result = await require("axios").get(
            blank, {
                responseType: "arraybuffer"
            }
        );
        ctx.body = new Buffer(result.data, "binary")
    }
});

router.get("/emp_file_service/file/:id/compressed/:size", async ctx => {
    try {
        let file = await util.getFile(ctx.params.id);
        ctx.type = file.type;

        ctx.body = await sharp(file.path)
            .resize(parseInt(ctx.params.size))
            .sharpen()
            // .webp()
            .toBuffer()
    } catch (e) {
        ctx.type = "image/svg+xml"
        let result = await require("axios").get(
            blank, {
                responseType: "arraybuffer"
            }
        );
        ctx.body = new Buffer(result.data, "binary")
    }
});

router.get("/emp_file_service/download", async ctx => {
    console.log(ctx.request.query.url)
    let result = await require("axios").get(
        ctx.request.query.url, {
            responseType: "arraybuffer",
            headers: {
                "Origin": "https://mp.weixin.qq.com"
            }
        }
    );
    console.log(result)
    ctx.body = new Buffer(result.data, "binary")
})

app.use(router.routes());

app.listen(config.port, () => {
    console.log(`koa is listening in ${config.port}`);
});